#include "stm32f10x.h"                  // Device header
/*Software SPI Mode 0*/
/*通信层*/

#define W25Q64_CS GPIO_Pin_4
#define W25Q64_SCK GPIO_Pin_5
#define W25Q64_MISO GPIO_Pin_6
#define W25Q64_MOSI GPIO_Pin_7

void MySPI_W_CS(uint8_t BitVal)
{
    GPIO_WriteBit(GPIOA, W25Q64_CS, (BitAction)BitVal);
}

void MySPI_W_SCK(uint8_t BitVal)
{
    GPIO_WriteBit(GPIOA, W25Q64_SCK, (BitAction)BitVal);
}

void MySPI_W_MOSI(uint8_t BitVal)
{
    GPIO_WriteBit(GPIOA, W25Q64_MOSI, (BitAction)BitVal);
}

uint8_t MySPI_R_MISO(void)
{
    return GPIO_ReadInputDataBit(GPIOA, W25Q64_MISO);
}

void MySPI_Start(void)
{
    MySPI_W_CS(0);
}

void MySPI_Stop(void)
{
    MySPI_W_CS(1);
}

//非移位模型 不会改变输入的数据
//如果需要改变相位，就把MySPI_W_SCK(1)和MySPI_W_SCK(0)提前一下
//如果需要改变极性，就把MySPI_W_SCK(1)和MySPI_W_SCK(0)换一下
//如果指只想接收数据的话发送W25Q64_DUMMY_BYTE
uint8_t MySPI_SwapByte(uint8_t SendByte)
{
    uint8_t i;
    uint8_t ReceiveByte = 0;
    for (i = 0; i < 8; i++)
    {
        MySPI_W_MOSI(SendByte & (0x01 << (7 - i)));         //逐位取出发送 (高位)
        MySPI_W_SCK(1);
        ReceiveByte = (ReceiveByte << 1) | MySPI_R_MISO();  //逐位接收
        MySPI_W_SCK(0);
    }
    return ReceiveByte;
}

void MySPI_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitTypeDef GPIO_InitStructure = 
    {
        .GPIO_Pin = W25Q64_CS | W25Q64_SCK | W25Q64_MOSI,
        .GPIO_Speed = GPIO_Speed_50MHz,
        .GPIO_Mode = GPIO_Mode_Out_PP                       //SPI需要推挽输出
    };
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = W25Q64_MISO;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    MySPI_W_CS(1);
    MySPI_W_SCK(0);
}

